from numpy import *
import operator


class KNN(object):
    group = []
    labels = 0

    def create_data_set(self):
        self.group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
        self.labels = ['A', 'A', 'B', 'B']

    def classify0(self, inx, k):
        data_set = self.group
        labels = self.labels
        data_set_size = data_set.shape[0]
        diff_mat = tile(inx, (data_set_size, 1)) - data_set
        sq_diff_mat = diff_mat ** 2
        sq_distances = sq_diff_mat.sum(axis=1)
        distances = sq_distances ** 0.5
        sorted_dist_indicies = distances.argsort()
        class_count = {}
        for i in range(k):
            vote_ilabel = labels[sorted_dist_indicies[i]]
            class_count[vote_ilabel] = class_count.get(vote_ilabel, 0) + 1
        sorted_class_count = sorted(class_count.items(), key=operator.itemgetter(1), reverse=True)
        return sorted_class_count[0][0]

